<template>
    <div id="wallet">
        <!-- 头部 -->
        <div class="top fs-12 fw-500">
            <div class="card">
                <div class="dis-flex flex-x-between flex-y-center">
                    <div>提现金额</div>
                    <div style="font-family: 'D-DIN">
                        余额：{{ summary.currentBalance }}元
                    </div>
                </div>
                <!-- 提现 -->
                <div class="withdraw dis-flex flex-x-between flex-y-center">
                    <span>￥</span>
                    <van-form>
                        <van-field
                            :border="false"
                            v-model="withdrawalAmount"
                            placeholder="请输入提现金额"
                            type="number"
                            label=""
                            :rules="[
                                {
                                    validator: validatorMoney,
                                    message: '请输入有效的金额格式',
                                },
                            ]"
                        />
                    </van-form>
                    <span @click="onAll">全部</span>
                </div>
                <div class="common-btn-big btn fw-600" @click="confirmWithdraw">
                    确认提现
                </div>
            </div>

            <!-- 统计 -->
            <div class="statistics fs-14 mt-16 fw-500 dis-flex flex-x-between">
                <div class="dis-flex flex-y-center flex-box">
                    <div class="mr-16">
                        <span>总奖励：</span>
                        <span style="font-family: 'D-DIN" class="col-3 mt-2">{{
                            summary.totalBackAmount
                        }}</span>
                    </div>
                    <div>
                        <span>总提现：</span>
                        <span style="font-family: 'D-DIN" class="col-3 mt-2">{{
                            summary.totalWithdrawalAmount
                        }}</span>
                    </div>
                </div>
                <div @click="onFillter" class="fillter dis-flex flex-y-center">
                    <span>筛选</span>
                    <img src="../../../assets/img/screen.svg" alt="" />
                </div>
            </div>

            <!-- 列表 -->
            <van-pull-refresh
                v-if="!loadData"
                v-model="refreshing"
                @refresh="onRefresh"
                success-text="刷新成功"
            >
                <van-list
                    v-model="loading"
                    :finished="finished"
                    finished-text="没有更多了"
                    @load="loadMore"
                    class="list"
                    :offset="100"
                    :immediate-check="false"
                    v-if="list.length !== 0"
                >
                    <div
                        v-for="(item, index) in list"
                        :key="index"
                        class="list-item dis-flex flex-y-start"
                    >
                        <div>
                            <img
                                src="../../../assets/img/shou.png"
                                alt=""
                                v-if="item.businessType == 1"
                            />
                            <img
                                src="../../../assets/img/zhi.png"
                                alt=""
                                v-if="item.businessType == 2"
                            />
                        </div>
                        <div class="flex-box">
                            <div
                                class="dis-flex fs-16 col-3 flex-x-between flex-y-center mb-12"
                            >
                                <p class="fw-500">
                                    {{ item.fundOperationsTypeName }}
                                </p>
                                <p
                                    class="fw-700 font"
                                    v-if="item.businessType == 1"
                                >
                                    +{{ item.operatingAmount }}
                                </p>
                                <p
                                    class="fw-700 font use"
                                    v-if="item.businessType == 2"
                                >
                                    -{{ item.operatingAmount }}
                                </p>
                            </div>
                            <div
                                class="fs-12 dis-flex flex-x-between flex-y-center"
                            >
                                <p>
                                    {{
                                        $utils.func.formatTime(item.createTime)
                                    }}
                                </p>
                                <!-- <p>审核中</p> -->
                            </div>
                        </div>
                    </div>
                </van-list>
                <van-empty v-else description="暂无内容" />
            </van-pull-refresh>

            <div v-else class="load">
                <van-loading color="#F53137" />
            </div>
        </div>

        <van-popup
            v-model="showPopup"
            :close-on-click-overlay="false"
            position="bottom"
        >
            <div class="popup-content">
                <div>
                    <div class="title">选择时间</div>
                    <div class="time dis-flex flex-y-center">
                        <div
                            class="date dis-flex flex-x-center flex-y-center"
                            @click="selTime(0)"
                        >
                            {{
                                filterContent.startTime
                                    ? $utils.func.formatYMDDate(
                                          filterContent.startTime
                                      )
                                    : "选择开始日期"
                            }}
                        </div>
                        <span>至</span>
                        <div
                            class="date dis-flex flex-x-center flex-y-center"
                            @click="selTime(1)"
                        >
                            {{
                                filterContent.endTime
                                    ? $utils.func.formatYMDDate(
                                          filterContent.endTime
                                      )
                                    : "选择结束日期"
                            }}
                        </div>
                    </div>
                </div>
                <div>
                    <div class="title">收支类型</div>
                    <div class="type-list fs-14 fw-400 dis-flex flex-x-between">
                        <div
                            class="dis-flex flex-x-center flex-y-center"
                            :class="{
                                'type-sel': selIndex === index,
                            }"
                            v-for="(item, index) in typeList"
                            :key="index"
                            @click="clickType(index)"
                        >
                            {{ item.type }}
                        </div>
                    </div>
                </div>
            </div>
            <div class="btn-view dis-flex flex-x-between fs-16 fw-400">
                <div @click="cancelFillter">取消</div>
                <div @click="confirmFillter">确定</div>
            </div>
        </van-popup>

        <!-- 日期选择器 -->
        <van-popup v-model="showPicker" position="bottom">
            <van-datetime-picker
                v-model="tradingTime"
                type="date"
                title="选择日期"
                :formatter="formatter"
                @confirm="onConfirm"
                @cancel="showPicker = false"
            />
        </van-popup>
    </div>
</template>

<script>
    import { Toast, Dialog } from 'vant';
    export default {
        props: [], // 父辈向子辈传参
        name: 'wallet',
        components: {
        },
        data() {
            return {
                showPopup: false,
                showPicker: false,
                tradingTime: new Date(),
                typeList: [
                    {
                        id: null,
                        type: '全部'
                    },
                    {
                        id: 1,
                        type: '收入'
                    },
                    {
                        id: 2,
                        type: '支出'
                    },
                ],
                selIndex: 0,
                filterContent: {
                    startTime: '',
                    endTime: '',
                    type: ''
                },
                timeType: 0, // 0 开始 1 结束
                size: 5,
                current: 1,
                loading: true,
                finished: false,
                refreshing: false,
                list: [],
                summary: {},
                withdrawalAmount: '',
                loadData: true
            }
        },
        methods: {
            formatter(type, val) {
                if (type === 'year') {
                    return `${val}年`;
                } else if (type === 'month') {
                    return `${val}月`;
                } else if (type === 'day') {
                    return `${val}日`;
                }
                return val;
            },
            validatorMoney(val) {
                return /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/.test(val)
            },
            onAll() {
                if (this.summary.currentBalance > 0) {
                    this.withdrawalAmount = this.summary.currentBalance
                } else {
                    this.$toast('暂无可提现余额')
                }
            },
            confirmWithdraw() {
                const { withdrawalAmount, summary } = this;
                if (!withdrawalAmount || withdrawalAmount <= 0) {
                    this.$toast('请输入提现金额');
                    return;
                }
                const amountRegex = /^([1-9]\d*|0)(\.\d{1,2})?$/;
                if (!amountRegex.test(withdrawalAmount)) {
                    this.$toast('请输入正确的金额格式');
                    return;
                }
                if (summary.currentBalance == 0 || parseFloat(withdrawalAmount) > parseFloat(summary.currentBalance)) {
                    this.$toast('您的余额不足');
                    return
                }

                if (this.summary.realNameState != 1) {
                    Dialog.confirm({
                        title: '提示',
                        message: '为了确保您的账户资金安全，请先完成实名认证。立刻前往“实名”页面操作吧！',
                        confirmButtonText: '前往'
                    })
                        .then(() => {
                            // this.$router.go(-1)
                            // this.$router.replace('/mine')
                            let url = window.location.origin + '/#/realname'
                            this.$api.accredit.getRemitCodeApi({
                                encryptUrl: encodeURIComponent(url)
                            }).then((res) => {
                                console.log("获取重定向结果", res);
                                this.$store.commit('setRealMark', 1)
                                window.location.href = res.data
                            }).catch((err) => {
                                console.log("获取重定向报错", err);
                            });
                        })
                        .catch(() => {
                        });
                    return
                }

                this.$toast.loading({
                    message: '提现中...',
                    forbidClick: true,
                    loadingType: 'spinner',
                })
                this.$api.app.walletWithdrawApi({
                    withdrawalAmount: parseFloat(withdrawalAmount).toFixed(2)
                })
                    .then((res) => {
                        console.log("提现结果", res);
                        if (res.code == 200) {
                            // Dialog.alert({
                            //     title: '提示',
                            //     message: '提现成功，预计1分钟内到账微信钱包，如未到账联系客服处理。',
                            // })
                            this.$toast.success('提现成功')
                            this.current = 1
                            this.withdrawalAmount = ''
                            this.incomeSummary()
                            // this.finished = false
                            // this.loadData = true
                            // this.getList()
                        } else {
                            this.$toast(res.message)
                        }
                    })
                    .catch((err) => {
                        console.log("err", err);
                        this.$toast(err.message)
                    });
            },
            onFillter() {
                this.showPopup = true
            },
            selTime(type) {
                this.showPicker = true
                this.timeType = type
            },
            onConfirm(value) {
                this.tradingTime = value
                // 开始
                if (this.timeType === 0) {
                    const endTime = new Date(this.filterContent.endTime || 0);
                    if (new Date(value) >= endTime && endTime > 0) {
                        this.$toast('开始日期不能晚于结束日期');
                        return;
                    }
                    this.filterContent.startTime = value;
                } else {
                    const startTime = new Date(this.filterContent.startTime || 0);
                    if (new Date(value) <= startTime && startTime > 0) {
                        this.$toast('结束日期不能早于开始日期');
                        return;
                    }
                    this.filterContent.endTime = value;
                }
                this.showPicker = false;
            },
            clickType(index) {
                this.selIndex = index
                this.filterContent.type = index
            },
            cancelFillter() {
                this.showPopup = false
                this.tradingTime = new Date()
                this.filterContent = {
                    startTime: '',
                    endTime: '',
                    type: ''
                }
                this.selIndex = 0
                this.current = 1
                this.getList();
            },
            confirmFillter() {
                if (this.filterContent.endTime !== '' && this.filterContent.startTime == '') {
                    this.$toast('请填写开始日期');
                    return
                }
                if (this.filterContent.startTime !== '' && this.filterContent.endTime == '') {
                    this.$toast('请填写结束日期');
                    return
                }
                this.loadData = true
                console.log("筛选", this.filterContent);
                this.showPopup = false
                this.current = 1
                this.finished = false
                this.list = []
                this.getList()
            },
            getList() {
                const { size, current, filterContent } = this;
                let { startTime, endTime, type } = filterContent;
                this.$toast.clear()

                // 函数来处理日期格式化
                const formatDateTime = (date) => {
                    return date ? this.$utils.func.formatDateTime(new Date(date)) : null;
                };

                let params = {
                    size,
                    current,
                    businessType: type,
                    createStartTime: formatDateTime(startTime),
                    createEndTime: formatDateTime(endTime),
                };
                // 删除空字符串参数
                for (let key in params) {
                    if (params[key] === "" || params[key] === null) {
                        delete params[key];
                    }
                }
                console.log("携带参数", params);

                console.log("refreshing", this.refreshing, this.finished);
                this.$api.app.walletListApi(params).then((res) => {
                    console.log("获取列表结果", res);
                    this.loadData = false
                    if (this.refreshing === true) {
                        // 下拉刷新
                        this.refreshing = false;
                        this.list = res.data.records
                        // this.loading = false;
                        if (this.list.length == res.data.total || res.data.records.length === 0) {
                            this.finished = true;
                        }
                    } else {
                        // 上拉加载
                        this.list = [...this.list, ...res.data.records];
                        this.loading = false;   // 加载状态结束
                        if (this.list.length == res.data.total || res.data.records.length === 0) {
                            this.finished = true;
                        }
                        this.loading = false
                    }
                }).catch((err) => {
                    console.log("err", err);
                    this.$toast(err.message)
                });
            },
            loadMore() {
                // 异步更新数据
                console.log("加载数据");
                if (this.refreshing) {
                    this.current = 1
                } else {
                    this.current++
                    this.getList();
                }
            },
            onRefresh() {
                this.refreshing = true
                this.finished = false
                this.current = 1
                this.getList()
            },
            incomeSummary() {
                this.$api.app.walletStatisticsApi().then((res) => {
                    // console.log("统计结果", res);
                    if (res.code == 200) {
                        this.summary = res.data
                        this.$store.commit('setUserInfo', res.data)
                    } else {
                        this.$toast(res.message)
                    }
                }).catch((err) => {
                    this.$toast(err.message)
                });
            }
        },
        computed: {},
        watch: {},
        created() { },
        mounted() {
            this.incomeSummary()
            this.getList()
            this.$store.commit('setRealMark', 0)
        },
    }
</script>
    
<style scoped lang='scss'>
    .top {
        width: 100%;
        height: 192px;
        background: url("../../../assets/img/Wallet_background.png");
        background-size: 100% 100%;
        padding: 16px 16px 0;
        box-sizing: border-box;

        .card {
            width: 344px;
            height: 200px;
            border-radius: 6px;
            background-color: #fff;
            padding: 16px 16px 0;
            box-sizing: border-box;

            .withdraw {
                margin-top: 42px;
                border-bottom: 0.5px solid #b4b4b4;
                padding-bottom: 14px;
                & > span:nth-child(1) {
                    font-weight: 500;
                    font-size: 24px;
                    color: #3d3d3d;
                    line-height: 24px;
                    margin-right: 8px;
                }
                .van-form {
                    flex: 1;
                    padding: 0;
                }
                .van-cell {
                    flex: 1;
                    padding: 0;
                    ::v-deep .van-field__control::-webkit-input-placeholder {
                        line-height: 14px;
                        font-size: 14px;
                        color: #666666;
                    }
                }
                & > span:last-child {
                    font-size: 14px;
                    color: #ff8610;
                    line-height: 14px;
                }
            }

            .btn {
                width: 264px;
                height: 48px;
                margin: 16px auto 0;
                background: #ff8610;
            }
        }
    }

    .statistics {
        box-sizing: border-box;
        color: #989898;
        .fillter {
            color: #333333;
            line-height: 18px;
            & > img {
                width: 16px;
                height: 16px;
                margin-left: 4px;
            }
        }
    }

    .load {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
    }
    .list {
        padding-bottom: 0px;
        min-height: 300px;
        .list-item {
            width: 344px;
            height: 88px;
            margin: 16px auto 0;
            background: #ffffff;
            border-radius: 6px;
            padding: 24px 24px 0;
            box-sizing: border-box;
            color: #989898;
            & > div:nth-child(1) {
                height: 100%;
                font-size: 0;
                margin-right: 16px;
                & > img {
                    width: 40px;
                    height: 40px;
                }
            }
            .font {
                font-family: "D-DIN";
            }
            .use {
                color: #ef4c4c;
            }
        }
    }

    .popup-content {
        padding: 16px 12px 15px;
        .title {
            font-weight: 600;
            font-size: 16px;
            color: #0b1526;
            line-height: 16px;
            margin-bottom: 12px;
        }
        .time {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 17px;
            & > span {
                margin: 0 10px;
            }
            .van-cell {
                border: 0.5px solid #d8d8d8;
                border-radius: 6px 6px 6px 6px;
                width: 158px;
                height: 40px;
                ::v-deep .van-field__body {
                    width: 100%;
                    height: 100%;
                    .van-field__control::-webkit-input-placeholder {
                        font-size: 14px;
                        color: #0b1526 !important;
                        line-height: 14px;
                        text-align: center;
                        font-weight: 400;
                    }
                    .van-field__control:disabled {
                        color: #0b1526 !important;
                        -webkit-text-fill-color: #0b1526 !important;
                        cursor: pointer;
                    }
                }
            }

            .date {
                width: 158px;
                height: 40px;
                border-radius: 6px 6px 6px 6px;
                border: 0.5px solid #d8d8d8;

                font-size: 14px;
                color: #0b1526 !important;
                text-align: center;
                font-weight: 400;
                box-sizing: border-box;
            }
        }

        .type-list {
            color: #0b1526;
            line-height: 14px;
            & > div {
                width: 109px;
                border-radius: 4px;
                background: #f6f8fa;
                line-height: 32px;
            }

            .type-sel {
                background: #ff8610;
                color: #ffffff;
            }
        }
    }
    .btn-view {
        border-top: 0.5px solid #e5e6eb;
        padding: 14px 12px 15px;
        & > div {
            width: 169px;
            height: 44px;
            background: #f6f8fa;
            border-radius: 23px;
            border: 0.1px solid #f6f8fa;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        & > div:nth-child(2) {
            background: #ff8610;
            color: #fff;
        }
    }

    .van-popup {
        border-radius: 8px 8px 0px 0px;
    }
</style>